package com.gqz.aircraftwar.mvp.main

import android.content.Intent
import android.graphics.*
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import com.gqz.aircraftwar.App
import com.gqz.aircraftwar.R
import com.gqz.aircraftwar.databinding.ActMainBinding
import com.gqz.aircraftwar.mvp.launch.LaunchAct
import com.gqz.aircraftwar.mvp.model.GameMap
import com.gqz.aircraftwar.mvp.model.aircraft.EnemyManager
import com.gqz.aircraftwar.mvp.model.aircraft.PlayerAircraft
import com.gqz.aircraftwar.mvp.model.bomb.BlastManager
import com.gqz.aircraftwar.mvp.model.buff.BuffManager
import com.gqz.aircraftwar.mvp.model.bullet.BulletManager
import com.gqz.aircraftwar.mvp.test.TestAct
import com.gqz.aircraftwar.mvp.view.Joystick
import com.gqz.aircraftwar.util.i
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.coroutines.*
import java.lang.Exception
import kotlin.coroutines.CoroutineContext
import kotlin.system.measureTimeMillis
import kotlinx.coroutines.Dispatchers.Main as UI

class MainAct : AppCompatActivity(), MainConstract.IView, SurfaceHolder.Callback,
    Joystick.OnJoystickChange, Observer<String> {

    private val TAG: String = "MainAct-->"

    private lateinit var binding: ActMainBinding
    private lateinit var presenter: MainConstract.IPresetner

    private lateinit var sv: SurfaceView
    private lateinit var holder: SurfaceHolder
    private lateinit var joystick: Joystick
    private val paint = Paint()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_main)
        binding = DataBindingUtil.setContentView(this, R.layout.act_main)
        binding.view = this

        MainPresenter(this)
        presenter.initPlayerInfo(intent)

        paint.isAntiAlias = true
        paint.isDither = true
        paint.color = Color.BLACK
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 3f

        sv = binding.mainSv
        holder = sv.holder
        holder.addCallback(this)

        joystick = binding.mainJoystick
        joystick.setOnJoystickChangeListener(this)

        LiveEventBus.get(
            App.EventKey.GameStatus_WaveOver, String::class.java
        ).observe(this, this)

    }

    override fun onResume() {
        super.onResume()
        i(TAG, "onResume-->")
        hideStatusBar()
    }

    override fun onDestroy() {
        super.onDestroy()
        i(TAG, "onDestroy-->")
        LiveEventBus.get(
            App.EventKey.GameStatus_WaveOver, String::class.java
        ).removeObserver(this)
        i(TAG, "onDestroy-->end")
    }

    override fun onChanged(t: String?) {
        i(TAG, "onChanged-->$t")
        toast(this, t ?: "")
    }

    override fun onChange(speedx: Float, speedy: Float) {
        if (speedx == 0f && speedy == 0f) {
            myAircraft.movable = false
        } else {
            myAircraft.movable = true
            myAircraft.move_x = speedx
            myAircraft.move_y = speedy
        }
    }

    /**
     * 全屏
     */
    private fun hideStatusBar() {
        val decorView = window.decorView
        val uiOptions = (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                or View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
        decorView.systemUiVisibility = uiOptions
    }

    override fun setIPresenter(presenter: MainConstract.IPresetner) {
        this.presenter = presenter
        lifecycle.addObserver(presenter)
        presenter.setBinding(binding)
    }

    //测试方法，可删除@FIXME
    fun onclick(v: View) {
        var intent = Intent(this, LaunchAct::class.java)
        intent.putExtra("exit", true)
        startActivity(intent)
    }

    //测试方法，可删除@FIXME
    fun generateBlast(v: View) {
        BuffManager.instance.generateBuff(PointF(10f, 10f))
        for (i in 1..5) {
//            BlastManager.instance.generateBlast(
//                PointF(
//                    (100..1000).random().toFloat(),
//                    (100..1000).random().toFloat()
//                )
//            )
//            BulletManager.instance.generateEnemyBullet(
//                PointF(
//                    (100..1000).random().toFloat(),
//                    (100..1000).random().toFloat()
//                ), (1..2).random().toFloat()
//            )
        }
    }

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
//        num(TAG, "surfaceChanged()")
        App.surfaceW = width
        App.surfaceH = height
        App.bounds = RectF(0f, 0f, width.toFloat(), height.toFloat())
        App.isRunning = true

        try {
            job = GlobalScope.launch(Dispatchers.Default) {
                i(TAG, "start--> mainWorks worked in ${Thread.currentThread().name}")

                var blastManager = BlastManager.instance
                var bulletManager = BulletManager.instance
                var enemyManager = EnemyManager.instance

                myAircraft.pos = PointF(
                    App.surfaceW / 2f - myAircraft.appearance.width / 2,
                    (App.surfaceH - myAircraft.appearance.height).toFloat()
                )
                var j = launch(UI) {
                    joystick.visibility = View.GONE
                }
                j.join()
                i(TAG, "surfaceChanged-->j1.completed=${j.isCompleted}")
//                runOnUiThread { joystick.visibility = View.GONE }

                var inGame = false
                var alpha = 255
                var canvas: Canvas? = null
                while (App.isRunning) {
                    try {
                        var h = this@MainAct.holder
                        canvas = h.lockCanvas()

                        if (canvas != null) {

                            if (inGame) {
                                GameMap.instance.draw(canvas)
                                myAircraft.draw(canvas)
                                enemyManager.drawAll(canvas)
                                bulletManager.drawAll(canvas)
                                blastManager.drawAll(canvas)
                                BuffManager.instance.drawAll(canvas)
                            } else {
                                alpha -= 3
                                if (alpha <= 0x10) {
                                    inGame = true
                                    var j = launch(UI) {
                                        //                                    println("***UI currentThread=${Thread.currentThread().name}")
                                        joystick.visibility = View.VISIBLE
                                    }
                                    j.join()
                                    i(
                                        TAG, "surfaceChanged--> j2.completed=${j.isCompleted}"
                                    )
//                                    runOnUiThread { joystick.visibility = View.VISIBLE }
                                    GameMap.instance.start()
                                    presenter.startGame()
                                    blastManager.start()
                                    bulletManager.start()
                                    myAircraft.start()
                                    enemyManager.start()
                                    BuffManager.instance.start()
                                } else {//入场效果
                                    GameMap.instance.draw(canvas)
                                    canvas.drawColor(
                                        Color.parseColor(
                                            "#" + alpha.toString(16) + "000000"
                                        )
                                    )
                                }
                            }
                        }

                    } catch (e: Exception) {
                        e.printStackTrace()
                    } finally {
                        if (canvas != null)
                            this@MainAct.holder?.unlockCanvasAndPost(canvas)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {
//        num(TAG, "surfaceDestroyed()")
        App.isRunning = false
        GameMap.instance.reset()
        PlayerAircraft.getInstant().stop()
        EnemyManager.instance.stop()
        BlastManager.instance.stop()
        BulletManager.instance.stop()
        BuffManager.instance.stop()
        PlayerAircraft.getInstant().reset()
        job.cancel()//不取消会导致程序退出
        runBlocking {
            job.join()
        }
        i(TAG, "surfaceDestroyed--> job.completed=${job.isCompleted}")
    }

    lateinit var job: Job
    var myAircraft = PlayerAircraft.getInstant()
    override fun surfaceCreated(holder: SurfaceHolder?) {
//        num(TAG, "surfaceCreated()")
    }

    override fun onBackPressed() {
        super.onBackPressed()
        i(TAG, "onBackPressed-->")
        App.isRunning = false
        finish()
    }
}